using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.RegionalPack
{
    [Serializable()]
    public class RegionalCidadeNameValueList : NameValueListBase<Guid, string>
    {
        #region Factory Methods
        private RegionalCidadeNameValueList()
        { /* require use of factory method */ }

        public static RegionalCidadeNameValueList GetRegionalCidadeNameValueList()
        {
            return DataPortal.Fetch<RegionalCidadeNameValueList>(new FilterCriteria());
        }

        public static RegionalCidadeNameValueList GetRegionalCidadeNameValueList(string inicial)
        {
            return DataPortal.Fetch<RegionalCidadeNameValueList>(new FilterCriteria(inicial));
        }
        #endregion //Factory Methods

        #region Data Access
        class FilterCriteria
        {
            public string Inicial = string.Empty;

            public FilterCriteria()
            {
            }

            public FilterCriteria(string inicial)
            {
                this.Inicial = inicial;
            }
        }

        private void DataPortal_Fetch(FilterCriteria criteria)
        {
            RaiseListChangedEvents = false;

            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            using (OdbcCommand cm = cn.CreateCommand())
            {
                IsReadOnly = false;
                cn.Open();

                cm.CommandType = CommandType.Text;
                cm.CommandText = "SELECT Id, Cidade from regionalcidadetb order by Cidade ASC ;";


                if (criteria.Inicial != string.Empty)
                    this.Add(new NameValuePair(Guid.Empty, criteria.Inicial));

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    while (dr.Read())
                        this.Add(new NameValuePair(new Guid(dr["Id"].ToString()), dr.GetString("Cidade")));
                }
                IsReadOnly = true;
            }//using

            RaiseListChangedEvents = true;
        }
        #endregion //Data Access
    }
}
